package com.yvon.maple.service.msg.core.websocket.processor;

import cn.hutool.json.JSONUtil;
import com.yvon.maple.service.msg.core.websocket.message.PublishMessage;
import com.yvon.maple.service.msg.core.websocket.message.SingleChatMessage;
import com.yvon.maple.service.msg.core.websocket.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Set;

/**
 * @author : Yvon
 * @since : 2021-12-07
 */
public class PublishProcessor extends Processor<PublishMessage> {
    @Override
    public void exec(Channel channel, String msg) {
        PublishMessage message = parse(msg);
        String content = message.getContent();
        String publisher = message.getPublisher();
        String type = message.getType();

        SingleChatMessage singleChatMessage = new SingleChatMessage();
        singleChatMessage.setContent(content);

        Set<Channel> subscribeList = SessionUtil.getSubscribeList(type);
        subscribeList.forEach(ch -> {
            if (ch.isActive()) {
                ch.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(singleChatMessage)));
            }
        });
    }
}
